export default {
  // socket参数
  socket: null,
  timeout: 1500, // 15秒一次心跳
  timeoutObj: null, // 心跳心跳倒计时
  serverTimeoutObj: null, // 心跳倒计时
  timeoutnum: null, // 断开 重连倒计时
  lockReconnect: false, // 防止
  // websocket: null,
  webSocket: Object,
  endData: Object,
  data: Object,
  type: 'a',
  baseUrl: '',
  runmessage: function (event) {
  },
  start1: function (returnMsgFun, error) {
    console.log('@@@@@')
    try {
      this.webSocket = new WebSocket(this.baseUrl)
      console.log('连接成功')
      let _this = this
      this.webSocket.onmessage = function (event) { // 获取消息
        console.log('e333')
        console.log(event, '获取服务器发送来的数据')
        if (event.data.indexOf('$*$') !== '-1') {
          let str = event.data.substring(3)
          event.data1 = str
        }
        _this.data = event
        _this.runmessage(event)
        if (typeof returnMsgFun === 'function') {
          returnMsgFun(event)
        }
      }
      this.webSocket.onerror = function (event) {
        if (typeof error === 'function') {
          error({ data: '连接失败' })
        }
      }
    } catch (e) {
      let _this = this
      this.webSocket.onmessage = function (event) {
        if (event.data.indexOf('$*$') !== '-1') {
          let str = event.data.substring(3)
          event.data1 = str
        }
        _this.data = event
        _this.runmessage(event)
      }
      if (typeof error === 'function') {
        error({ data: '没有发现设备' })
      }
    }
  },
  cat: function () {
    this.endData = this.data
    // this.sendMsg('bStopPlay')
  },
  sendMsg: function (msg) {
    try {
      this.webSocket.send(msg)
    } catch (e) {
      console.log(e, '9999991')
    }
  },
  over: function () {
    this.webSocket.send('bStopPlay()')
  },
  close: function () {
    this.webSocket.send('bStopPlay()')
  },
  initWebSocket: function () {
    // ws等同于http，wss等同于https
    this.webSocket = new WebSocket(this.baseUrl)
    // this.webSocket = new WebSocket(wsUrl)
    this.webSocket.onopen = this.websocketonopen
    this.webSocket.onerror = this.websocketonerror
    this.webSocket.onmessage = this.setOnmessageMessage
    this.webSocket.onclose = this.websocketclose
  },
  start: function () {
    console.log('start')
    // 清除延时器
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    this.timeoutObj = setTimeout(() => {
      if (this.webSocket && this.webSocket.readyState == 1) {
        var data = { 'code': 1, 'msg': '心跳', 'data': '心跳' }
        this.webSocket.send(JSON.stringify(data)) // 给服务端定时发送消息，保持链接
      } else {
        this.reconnect()
      }
      // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
      this.serverTimeoutObj = setTimeout(() => {
        this.webSocket.close()
      }, this.timeout)
    }, this.timeout)
  },
  reset () { // 重置心跳
    // 清除时间
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
    // 重启心跳
    this.start()
  },
  // 重新连接
  reconnect () {
    console.log('重连')
    if (this.lockReconnect) return
    this.lockReconnect = true
    // 没连接上会一直重连，设置延迟避免请求过多
    this.timeoutnum && clearTimeout(this.timeoutnum)
    this.timeoutnum = setTimeout(() => {
      this.initWebSocket()
      this.lockReconnect = false
    }, 20000)
  },
  // 监听消息(接收服务端返回的数据)
  async setOnmessageMessage (event) {
    console.log('接受消息')
    this.reset()
    // 自定义全局监听事件
    window.dispatchEvent(new CustomEvent('onmessageWS', {
      detail: {
        data: event.data
      }
    }))
  },
  websocketonopen () {
    // 开启心跳
    console.log('开启心跳')
    this.start()
    console.log('WebSocket连接成功')
  },
  websocketonerror (e) {
    console.log('WebSocket连接发生错误' + e)
  },
  websocketclose (e) {
    this.webSocket.close()
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
    console.log('WebSocket连接关闭')
    // websocket关闭后重新尝试连接,保持心跳
    setTimeout(() => {
      this.reconnect()
    }, 5000)
  },
  websocketsend (messsage) {
    this.webSocket.send(messsage)
  },
  closeWebSocket () { // 关闭websocket
    this.webSocket.close()
  }
}
